package com.jinxin.platform.cdelecinspect.controller;

import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.base.common.support.BaseController;
import com.jinxin.platform.cdelecinspect.utils.GetIpAndPort;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/upload")
public class FileUploadController
        extends BaseController {
    @Value("${platform.upload}")
    private String uploadPath;

    @PostMapping("/moduleUploadFile")
    public JsonResult moduleUploadFile(@RequestParam("file") MultipartFile file,
                                       @RequestParam("moduleKey") String moduleKey,
                                       @RequestParam("filePath") String filePath,
                                       @RequestParam(value = "fileName", defaultValue = "") String fileName,
                                       @RequestParam(value = "cover", defaultValue = "0") String cover) throws Exception {
        String ipAndPort = GetIpAndPort.getIpAndPort();
        System.out.println(ipAndPort);

        if (StringUtils.isBlank(moduleKey)) {
            return JsonResult.error("moduleKey不能为空");
        }
        if (StringUtils.isBlank(filePath)) {
            return JsonResult.error("filePath不能为空");
        }
        if (StringUtils.isBlank(fileName)) {
            fileName = file.getOriginalFilename();
        }
        filePath = filePath.replace("\\", "/");
        if (!filePath.startsWith("/")) {
            filePath = "/" + filePath;
        }
        fileName = fileName.replace("\\", "/");
        if (!fileName.startsWith("/")) {
            fileName = "/" + fileName;
        }
        String fileSavePath = "/module/" + moduleKey + filePath + fileName;
        String targetPath = this.uploadPath + fileSavePath;
        File targetFile = new File(targetPath);
        if ((targetFile.exists()) && (!"1".equals(cover))) {
            return JsonResult.error("文件已存在，请确认或修改文件名！");
        }
        if (!targetFile.getParentFile().exists()) {
            targetFile.getParentFile().mkdirs();
        }
        targetFile.createNewFile();
        file.transferTo(targetFile);

        Map<String, String> map = new HashMap();
        map.put("fileSavePath", fileSavePath);


        return JsonResult.ok(map);
    }

}
